//
//  Utility.swift
//  AIPhotoProcess
//
//  Created by aw031 on 17/10/2025.
//

import Foundation
import UIKit
// MARK: - Block 类型定义
public typealias ClickBlock = () -> Void
public typealias StringBlock = (_ text: String) -> Void
public typealias IndexBlock = (_ tag: Int) -> Void

public typealias StringAndIndexBlock = (_ text: String, _ tag: Int) -> Void

public typealias EventClickBlock = (_ btn: UIButton) -> Void

public typealias EventAndIndexBlock = (_ btn: UIButton, _ tag: Int) -> Void

public typealias DialogClickBlock = (_ btnTag : Int ,_ dialogTag : Int ) -> Void


public typealias ViewBlock = (_ view: UIView) -> Void

public typealias ImageBlock = (_ image: UIImage) -> Void

public typealias StatusBlock = (_ success: Bool) -> Void

public typealias StatusAndDataBlock = (_ success: Bool, _ result: Any?) -> Void

public typealias StatusAndURLBlock = (_ success: Bool, _ result: URL?) -> Void

public typealias SliderChangeValueBlock = (_ slider : UISlider) -> Void



public struct Utility {
    
    /// 主要用于中文输入场景，限制拼音字符输入
    public static func allowMaxStringLength(_ length: Int) -> Int {
        if length > 2 {
            return Int.max
        } else if length > 0 {
            return length * 6
        }
        return 0
    }


    /// 有效数字
    public static func dealingWithDecimals(value: CGFloat) -> String {
        return dealingWithDecimals(value: value, maximumFractionDigits: 1)
    }
    public static func dealingWithDecimals(value: CGFloat, maximumFractionDigits: Int) -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = maximumFractionDigits
        formatter.roundingMode = .halfUp
        return formatter.string(from: NSNumber(value: Double(value))) ?? ""
    }
    
    
    static func getApplication() -> UIApplication? {
         guard let screen = UIScreen.main as? UIScreen else { return nil }
         
         // 获取 _preferredFocusedWindow
         guard let window = screen.value(forKey: "_preferredFocusedWindow") as? UIWindow else {
             return nil
         }

         var responder: UIResponder? = window.next

         // 遍历 nextResponder，直到找到 UIApplication
         while responder != nil, !(responder is UIApplication) {
             responder = responder?.next
         }

         return responder as? UIApplication
     }
     
     /// 比较本地版本是否是最新版本
         /// - Parameters:
         ///   - localVersion: 本地版本号
         ///   - upToDateVersion: 最新版本号
         /// - Returns: 如果最新版本比本地版本新，返回 true
     static func needUpdataVersoin(_ currentVersion: String, appNewVersion: String) -> Bool {
         //
         // 如果最新版本为空，返回 false
         guard !appNewVersion.isEmpty else {
             return false
         }
         
         // 如果本地版本为空，认为需要更新
         guard !currentVersion.isEmpty else {
             return true
         }
         
         let localComponents = currentVersion.components(separatedBy: ".")
         let upToDateComponents = appNewVersion.components(separatedBy: ".")
         
         let maxLength = max(localComponents.count, upToDateComponents.count)
         
         for i in 0..<maxLength {
             // 获取对应位置的版本号数字，如果不存在则补0
             let upToDatePart = i < upToDateComponents.count ? (Int(upToDateComponents[i]) ?? 0) : 0
             let localPart = i < currentVersion.count ? (Int(localComponents[i]) ?? 0) : 0
             
             if upToDatePart > localPart {
                 return true
             } else if upToDatePart < localPart {
                 return false
             }
             // 如果相等，继续比较下一级
         }
         
         // 所有部分都相等，说明版本相同，不需要更新
         return false
     }
    
    static func configureEncoder() -> JSONEncoder {
        let encoder = JSONEncoder()
        
        encoder.outputFormatting = .prettyPrinted
        // 设置date编码策略
        encoder.dateEncodingStrategy = .iso8601
        // 设置Data编码策略
        encoder.dataEncodingStrategy = .base64
        return encoder
    }
    
    static func configureDecoder() -> JSONDecoder {
        let decoder = JSONDecoder()
        // 设置date编码策略
        decoder.dateDecodingStrategy = .iso8601
        // 设置Data解码策略
        decoder.dataDecodingStrategy = .base64
        return decoder
    }
    
    public static func allowMaxMarkLength(_ remainLength: Int) -> Int {
        var length = 0
        if remainLength > 2 {
            length = NSInteger.max
        } else if remainLength > 0 {
            length = remainLength * 6 //一个中文对应的拼音一般不超过6个
        }
        return length
    }
    
    
    /// 复制文字
    public static func copy(text: String) {
        let str = text.trimmingCharacters(in: .whitespaces)
        if str.isEmpty {
            MBProgressHUD.showCustomToast(message: CopyFailTip )
        } else {
            UIPasteboard.general.string = text
            MBProgressHUD.showCustomToast(message: CopySuccessTip )
        }
    }
    
    
    /// 跳转外链
    public static func openExternalLink(urlString: String) {
        guard !urlString.isEmpty, let url = URL(string: urlString) else { return }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    
    /// 分享APP
    public static func shareApp(target: UIViewController?) {
        let shareTitle = UIDevice.appName
        let shareURL = URL(string: "https://itunes.apple.com/us/app/id\(KAppID)")! //
        let activityItems: [Any] = [shareTitle, shareURL]
        let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        activityVC.completionWithItemsHandler = { _, completed, _, _ in
            KLog(completed ? "成功" : "取消")
        }
        target?.present(activityVC, animated: true, completion: nil)
    }
    
    /// 分享文件
    public static func shareFile(activityItems : [Any],target: UIViewController? , completion :UIActivityViewController.CompletionWithItemsHandler? = nil) {
        //        let shareTitle = UIDevice.appName
        //        let shareURL = URL(string: "https://itunes.apple.com/us/app/id\(KAppID)")! //
        //        let activityItems: [Any] = [shareTitle, shareURL]
        let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        
        activityVC.completionWithItemsHandler = { (activityType, completed,returnedItems, error) in
            if let block = completion {
                block(activityType, completed,returnedItems, error)
            }
            KLog(completed ? "成功" : "取消")
        }
        target?.present(activityVC, animated: true, completion: nil)
    }
    
}
